package com.lv.suyiyong.hfr.ui

import android.content.Intent
import android.graphics.Color
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SizeUtils
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.lv.common.base.BaseActivity
import com.lv.common.bean.CommonSelectedBean
import com.lv.common.dialog.HintDialog
import com.lv.common.imp.OnPositionTListener
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.MyUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.service.bean.CompanyBean
import com.lv.service.model.EditorViewModel
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.room.address.AddressBean
import com.lv.service.room.address.AddressDbHelper
import com.lv.service.room.company.CompanyItemBean
import com.lv.service.utils.UserUtils
import com.lv.service.weidget.picker.ListSingleTextPopupView
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.FactoryAdapter
import com.lv.suyiyong.hfr.databinding.ActivityCompanyInfoBinding
import com.lv.suyiyong.hfr.fragment.CompanyCategoryLRFragment
import com.lv.suyiyong.hfr.fragment.CompanyFactoryFragment
import com.lv.suyiyong.hfr.fragment.CompanyHomeFragment
import com.lv.suyiyong.hfr.fragment.CompanyProductFragment
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupPosition
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2025/8/12 上午10:21
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 *
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：公司详情
 */
@Route(path = ARoutUtils.CompanyInfoActivity)
class CompanyInfoActivity : BaseActivity<ActivityCompanyInfoBinding>(), View.OnClickListener {
    @Autowired(name = "subType")
    @JvmField
    var mSubType: String? = null

    @Autowired(name = "cpyid")
    @JvmField
    var cpyid: String = ""

    @Autowired(name = "fcaid")
    @JvmField
    var mFcaid: String = ""

    @Autowired(name = "secaid")
    @JvmField
    var mSecaid: String = ""


    @Autowired(name = "province")
    @JvmField
    var mProvince: String = ""
    private var mLocalDisplay: String = ""
    private var mHalf: String = ""//  0/null 不显示弹窗。  1 显示灰色。  2两个模式都有
    private var mLoadLogin: Boolean = false
    private var mFristApply: Boolean = false//是否是首单
    private var mCompanyItemBean: CompanyItemBean? = null
    private var mApproveId = ""//分享的ID

    //    private var mCashType: Int = 1//0 仅海南 1 其它
    private var page: Int = 1
    private var pageSize: Int = Constants.pageSize

    private var mTxaccid: String = ""
    private var mCompanyCpName: String = ""
    private var mBname: String = ""
    private var mLogo: String = ""
    private var mCategory: String = ""
    private var mCategoryName: String = ""
    private val mEditorViewModel by viewModels<EditorViewModel>()
    private val serviceViewModel: ServiceViewModel by viewModel()
    private var mIsShow: Boolean = true//标记是否显示，显示时积分定时器才走

    private var currentFragment: Fragment? = null
    private val viewModel: ServiceViewModel by viewModel()
    private val paramsMap = mutableMapOf<String, String>()
    private val tabList = mutableListOf<TabLayout.Tab>()
    private val mBean = mutableListOf<CompanyItemBean>()
    private var mAdapter: FactoryAdapter? = null
    private var mIsFristLoading = true
    private var isLogin: Boolean = false

    //    private var isNewCompany: Boolean = false
    private var mNewTemplate: String = "0"
    private var mCastyle: String = "0"
    private val titles = arrayOf("首页", "产品", "", "工厂", "客服").toList()
    private var lastTab = 0

    //0  普通  1 银牌  2 金牌
    private var mIsspecially = ""
    private var mPhone = ""

    private var fragments = mutableListOf<Fragment>()
    private var mBindAliPay = false
    private val mAddressBean = mutableListOf<AddressBean>()

    //    private var mShowCouponDialog = false//是否弹优惠券的弹窗
    private var mUserInfo: UserInfo? = null
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())

    private val icons = intArrayOf(
        R.drawable.ic_company_home,
        R.drawable.ic_company_product, 0,
        R.drawable.ic_company_factory,
        R.drawable.ic_company_service
    )
    private val iconsNew = intArrayOf(
        R.drawable.ic_company_home_theme,
        R.drawable.ic_company_product_theme, 0,
        R.drawable.ic_company_factory_theme,
        R.drawable.ic_company_service_theme
    )

    override fun getLayoutRes() = R.layout.activity_company_info
    override fun initView() {
        super.initView()
        ARouter.getInstance().inject(this)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@CompanyInfoActivity, viewSub)
            StatusBarUtil.setHeightAndPadding(this@CompanyInfoActivity, titleBar)
            titleBar.onClickBackIcon {
                finish()
            }
            initSingleClickListener(viewTel, ivShare, ivBack)
        }

    }


    override fun initConfig() {
        super.initConfig()
        showLoadErrorView("页面加载中……")
        initParams()
        lifecycleScope.launchWhenCreated {
            val taskAddress = async {
                val addressList = getAddressForDB()
                mAddressBean.clear()
                addressList?.let { mAddressBean.addAll(it) }
            }
            val taskUserInfo = async {
                mUserInfo = getUserInfoForDB()
                isLogin = !mUserInfo?.id.isNullOrEmpty()
            }
            val findCompanyNet = async {
                val result = findOneCompany()
                parseFindOneCompanyResult(result)

            }

            taskAddress.await()
            taskUserInfo.await()
            findCompanyNet.await()
            initCompanyInfo()
        }

    }

    private fun initParams() {
        if (intent != null) {
            cpyid = intent.getStringExtra("cpyid") ?: ""
        }
        paramsMap["cpyid"] = cpyid
        if (mFcaid.isNotEmpty()) {
            paramsMap["fcaid"] = mFcaid
        }
        if (mSecaid.isNotEmpty()) {
            paramsMap["secaid"] = mSecaid
        }

        if (!mSubType.isNullOrEmpty()) {
            paramsMap["subType"] = mSubType ?: ""
        }
        if (mProvince.isNotEmpty()) {
//            mProvince = SPStaticUtils.getString(Constants.SP_KEY_ADDRESS_PROVINCE, "")
            paramsMap["province"] = mProvince
        }
    }

    private suspend fun getAddressForDB(): List<AddressBean>? {
        val list = withContext(Dispatchers.IO) {
            AddressDbHelper.getFindAllAddressSuspend(this@CompanyInfoActivity)
        }
        return list
    }

    private suspend fun getUserInfoForDB(): UserInfo? {
        val list = withContext(Dispatchers.IO) {
            UserDbHelper.getUserInfo(this@CompanyInfoActivity)
        }
        return list
    }

    private suspend fun findOneCompany(): DataResult<BaseYgxRsp> {
        return withContext(Dispatchers.IO) {
            myScope.async {
                viewModel.findOneCompany(paramsMap)
            }.await()
        }
    }


    private fun initCompanyInfo() {
        if (mCompanyItemBean != null) {
            if (mIsFristLoading) {
                mBinding.viewSub.visibility = View.VISIBLE
                fragments.clear()
                fragments.add(CompanyHomeFragment.newInstance(mCompanyItemBean!!))
                fragments.add(CompanyProductFragment.newInstance(mCompanyItemBean!!))
                fragments.add(CompanyFactoryFragment.newInstance(mCompanyItemBean!!))
                switchFragment(fragments[0])
            } else {
//                LiveEventBus.get(CompanyEvent::class.java).post(CompanyEvent(mCompanyItemBean))
            }
            when (mIsspecially) {
                "2" -> {
                    mBinding.viewTel.LoadSrc(Constants.company_info_bottom_orange_phone)
                    initTabLayout(
                        titles,
                        icons,
                        com.lv.common.R.color.home_text_color_select_new
                    )
                }

                else -> {
                    mBinding.viewTel.LoadSrc(Constants.company_info_bottom_theme_phone)
                    initTabLayout(
                        titles, iconsNew, R.color.home_bottom_select
                    )
                }
            }
            mIsFristLoading = false
            setTabClickEvent()
        }
    }

    private fun initTabLayout(titles: List<String>, iconsNew: IntArray, color: Int) {
        for (i in titles.indices) {
            val customView =
                mBinding.tabLayout.newTab()
                    .setCustomView(com.lv.common.R.layout.view_home_tab)
            val ivTabIcon =
                customView.customView?.findViewById<ImageView>(com.lv.common.R.id.iv_tab_icon)
            val tvTabTitle =
                customView.customView?.findViewById<TextView>(com.lv.common.R.id.tv_tab_title)
            ivTabIcon?.setImageResource(iconsNew[i])
            tvTabTitle?.text = titles[i]
            mBinding.tabLayout.addTab(customView)
            tvTabTitle?.setTextColor(resources.getColorStateList(color))
            tabList.add(customView)
        }
    }


    private fun parseFindOneCompanyResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<CompanyItemBean> { code, data, message, result ->
                data?.let {
                    mCompanyItemBean = it
//                    mHalf = it.ishalf ?: ""
                    mTxaccid = it.txaccid ?: ""
                    mCompanyCpName = it.name ?: ""
                    mLogo = it.image ?: ""
                    mBname = it.bnames ?: ""
                    val contact = it.contact
                    mPhones.clear()
//                    val companytel = it.companytel ?: ""
//                    if (companytel.isNotEmpty()) {
//                        mPhones.add(CommonSelectedBean(companytel))
//                    }
                    if (!contact.isNullOrEmpty()) {
                        contact.forEach { contarcItem ->
                            val tel = contarcItem.tel
                            if (!tel.isNullOrEmpty()) {
                                mPhones.add(CommonSelectedBean(tel))
                            }
                        }
                    }
                    val phone = it.phone
                    if (!phone.isNullOrEmpty()) {
                        mPhones.add(CommonSelectedBean(phone))
                    }
                    val newList = mPhones.distinctBy { it.name }
                    mPhones.clear()
                    mPhones.addAll(newList)
                    mCategory = it.secaid ?: ""
                    mCategoryName = it.secname ?: ""
//                    mNewTemplate = it.newtemplate// 0 新样式 其它 老样式
//                    val address = SPStaticUtils.getString(Constants.SP_KEY_ADDRESS_PROVINCE, "湖北")
//                    isNewCompany = newtemplate == "0"
//                    mDisplay = it.display ?: ""
                    //0  普通  1 银牌  2 金牌
                    mIsspecially = it.isspecially ?: "0"
                    when (mIsspecially) {
                        "2" -> {
                            initStatusBar(this@CompanyInfoActivity, true, false)
                            mBinding.viewTopBg.setBackgroundResource(com.lv.common.R.drawable.bg_3e_1c)
                            mBinding.llSearch.setBackgroundResource(com.lv.common.R.drawable.bg_f4_tr_30_16)
                            mBinding.ivBack.setImageResource(com.lv.common.R.drawable.icon_back_white_goods)
                            mBinding.ivShare.setImageResource(R.drawable.icon_share_goods_white)
                            mBinding.viewTopSubBg.setBackgroundColor(Color.parseColor("#1C1C1C"))
                        }

                        else -> {
                            initStatusBar(this@CompanyInfoActivity, true, true)
                            mBinding.llSearch.setBackgroundResource(com.lv.common.R.drawable.bg_f4_16)
                            mBinding.ivBack.setImageResource(com.lv.common.R.drawable.icon_back_black_goods)
                            mBinding.ivShare.setImageResource(R.drawable.icon_share_goods_black)
                            mBinding.viewTopSubBg.setBackgroundColor(Color.parseColor("#ffffff"))
                        }
                    }
//                    mIsOpen = it.isopen ?: "0"
//                    mLocalDisplay = it.localdisplay ?: ""
//                    LiveEventBus.get(CompanyEvent::class.java).post(CompanyEvent(it))
//                    changeLocation(data.localdisplay ?: "")
                }

            }
            onBizError<CompanyItemBean> { code, message, data ->
                setCompanyDeleteUI()
//                showToast(message)
            }
        }
        data.onFailure {
            showLoadErrorView("店铺有误", showBack = true) { finish() }
        }
    }

//    private fun changeLocation(localdisplay: String) {
//        val province = SPStaticUtils.getString(Constants.SP_KEY_ADDRESS_PROVINCE, "")
//        if (!province.isNullOrEmpty() && localdisplay.isNotEmpty()) {
//            if (province.contains(localdisplay) || localdisplay.contains(province)) {
//
//            } else {
//                for (address in mAddressBean) {
//                    val name = address.name
//                    if (name.contains(localdisplay) || localdisplay.contains(name)) {
//                        val telSecondCategories = address.telSecondCategories
//                        val city = telSecondCategories?.get(0)?.name ?: ""
//                        val area =
//                            telSecondCategories?.get(0)?.telThirdCategories?.get(0)?.name ?: ""
//                        YgxRoomToolsKt.saveLoction(
//                            this@CompanyInfoActivity,
//                            address.forshort, address.name, city, area, "", ""
//                        )
//                        break
//                    }
//                }
//
//            }
//        }
//    }


    override fun initData() {
        super.initData()

    }

    fun setTabSelected(position: Int) {
        mBinding.tabLayout.selectTab(mBinding.tabLayout.getTabAt(position))
    }

    private fun setTabClickEvent() {
        mBinding.tabLayout.addOnTabSelectedListener(object : OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                val selectedTabPosition = mBinding.tabLayout.selectedTabPosition
                when (mNewTemplate) {
                    "0" -> {
                        mBinding.viewSub.visibility = View.VISIBLE
                        if (selectedTabPosition == 4) {//客服
                            if (isLogin) {
                                UserUtils.showChatActivity(mTxaccid, mCompanyCpName)
                                savecallnum()
                            } else {
                                ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL)
                                    .navigation()
                            }
                            mBinding.tabLayout.selectTab(mBinding.tabLayout.getTabAt(lastTab))
                            return
                        } else if (selectedTabPosition == 3) {
                            switchFragment(fragments[2])
                            lastTab = selectedTabPosition ?: 0
                        } else if (selectedTabPosition == 2) {
                            //                        YgxUtilsKt.callPhone(this@CompanyInfoActivity, mPhone)
                        } else {
                            switchFragment(fragments[selectedTabPosition ?: 0])
                            lastTab = selectedTabPosition ?: 0
                        }
                    }

                    "1" -> {
                        if (selectedTabPosition == 4) {//客服
                            if (isLogin) {
                                mBinding.viewSub.visibility = View.VISIBLE
                                UserUtils.showChatActivity(mTxaccid, mCompanyCpName)
                                savecallnum()
                            } else {
                                ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL)
                                    .navigation()
                            }
                            mBinding.tabLayout.selectTab(mBinding.tabLayout.getTabAt(lastTab))
                            return
                        } else if (selectedTabPosition == 3) {
                            mBinding.viewSub.visibility = View.VISIBLE
                            switchFragment(fragments[2])
                            lastTab = selectedTabPosition ?: 0
                        } else if (selectedTabPosition == 2) {
                            //                        YgxUtilsKt.callPhone(this@CompanyInfoActivity, mPhone)
                        } else if (selectedTabPosition == 1) {
                            switchFragment(fragments[selectedTabPosition ?: 0])
                            lastTab = selectedTabPosition ?: 0
                            mBinding.viewSub.visibility = View.VISIBLE
                        } else {
                            mBinding.viewSub.visibility = View.GONE
                            switchFragment(fragments[selectedTabPosition ?: 0])
                            lastTab = selectedTabPosition ?: 0
                        }
                    }

                    "2" -> {
                        if (selectedTabPosition == 4) {//客服
                            if (isLogin) {
                                mBinding.viewSub.visibility = View.VISIBLE
                                UserUtils.showChatActivity(mTxaccid, mCompanyCpName)
                                savecallnum()
                            } else {
                                ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL)
                                    .navigation()
                            }
                            mBinding.tabLayout.selectTab(mBinding.tabLayout.getTabAt(lastTab))
                            return
                        } else if (selectedTabPosition == 3) {
                            mBinding.viewSub.visibility = View.VISIBLE
                            switchFragment(fragments[2])
                            lastTab = selectedTabPosition ?: 0
                            initStatusBar(this@CompanyInfoActivity, true, true)
                        } else if (selectedTabPosition == 2) {
                            initStatusBar(this@CompanyInfoActivity, true, true)
                            //                        YgxUtilsKt.callPhone(this@CompanyInfoActivity, mPhone)
                        } else if (selectedTabPosition == 1) {
                            initStatusBar(this@CompanyInfoActivity, true, true)
                            switchFragment(fragments[selectedTabPosition ?: 0])
                            lastTab = selectedTabPosition ?: 0
                            mBinding.viewSub.visibility = View.VISIBLE
                        } else {
                            initStatusBar(this@CompanyInfoActivity, true, false)
                            mBinding.viewSub.visibility = View.GONE
                            switchFragment(fragments[selectedTabPosition ?: 0])
                            lastTab = selectedTabPosition ?: 0
                        }
                    }

                    else -> {
                        mBinding.viewSub.visibility = View.VISIBLE
                        if (selectedTabPosition == 3) {//客服
                            if (isLogin) {
                                UserUtils.showChatActivity(mTxaccid, mCompanyCpName)
                                savecallnum()
                            } else {
                                ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL)
                                    .navigation()
                            }
                            mBinding.tabLayout.selectTab(mBinding.tabLayout.getTabAt(lastTab))
                            return
                        } else {
                            switchFragment(fragments[selectedTabPosition ?: 0])
                            lastTab = selectedTabPosition ?: 0
                        }
                    }

                }

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })
    }


    private fun switchFragment(fragment: Fragment) {
        if (currentFragment == fragment) {
            return
        }
        supportFragmentManager.fragments.forEach {
            if (it.isAdded && !it.isHidden) {
                supportFragmentManager.beginTransaction().hide(it).commit()
            }
        }
        if (!fragment.isAdded) {
            supportFragmentManager.beginTransaction().add(R.id.fl_container, fragment).commit()
        } else {
            supportFragmentManager.beginTransaction().show(fragment).commit()
        }
        currentFragment = fragment

    }

    inner class Adapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
        override fun getItem(position: Int): Fragment {
            return fragments[position]
        }

        override fun getCount(): Int {
            return fragments.count()    //返回此集合中的元素数
        }
    }

    /**
     * 店铺不存在
     */
    private fun setCompanyDeleteUI() {
        mBinding.clParent.visibility = View.GONE
        mBinding.clContainer.visibility = View.VISIBLE
        mBinding.titleBar.setTitle("店铺过期不存在")
        mAdapter = FactoryAdapter(mBean)
        val headerView = layoutInflater.inflate(
            R.layout.layout_goods_details_delete_header, null, false
        )
        headerView.findViewById<TextView>(R.id.tv_tip_small).text = "店铺过期不存在"
        headerView.findViewById<TextView>(R.id.tv_tip).text = "推荐店铺"
        mBinding.rvContent.adapter = mAdapter
        mAdapter?.addHeaderView(headerView)
        mBinding.rvContent.addItemDecoration(SpacesItemDecoration(SizeUtils.dp2px(10.0f), 0, true))
        recommendCompany()
        mAdapter?.onViewClickListener = OnPositionTListener { position, data ->
            ARouter.getInstance().build(ARoutUtils.CompanyInfoActivity)
                .withString("cpyid", data.id)
                .navigation()
            finish()
        }
//        mAdapter?.onChatClickListener = OnPositionTListener { position, data ->
//            if (isLogin) {
//                val txaccid = data.txaccid
//                val mCompanyCpName = data.name
//                UserUtils.showChatActivity(txaccid, mCompanyCpName)
//                savecallnum()
//            } else {
//                ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL).navigation()
//            }
//        }

    }


    private fun recommendCompany() {
//        startLoading()
        val recomMap = mutableMapOf<String, String>()
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { viewModel.findGoodsbotton(page, pageSize, recomMap) }.await()
            parseRecommendCompanyResult(result)
        }

    }

    private fun parseRecommendCompanyResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<CompanyBean> { code, data, message, result ->
                data?.let {
                    val items = it.items
                    MyUtils.recyclerviewSetData(
                        page, pageSize, mBinding.refresh, mBean, items, mAdapter
                    )
                }

            }
            onBizError<Any> { code, message, data ->
                showToast(message)
                mBinding.refresh.finishRefresh()
                mBinding.refresh.finishLoadMore()
            }
        }
        data.onFailure {
            mBinding.refresh.finishRefresh()
            mBinding.refresh.finishLoadMore()
        }
    }

    private fun savecallnum() {
//        lifecycleScope.launchWhenCreated {
//            val result: DataResult<BaseYgxRsp> =
//                myScope.async { serviceViewModel.savecallnum(cpyid) }.await()
//
//        }
    }

    private fun sendCallMessage() {
//        lifecycleScope.launchWhenCreated {
//            val result: DataResult<BaseYgxRsp> =
//                myScope.async { serviceViewModel.sendCallMessage(mPhone) }.await()
//        }
    }

    override fun initEvents() {
        super.initEvents()

        registEventBus()
    }

    private fun registEventBus() {


    }

    override fun onResume() {
        super.onResume()
        GSYVideoManager.instance().isNeedMute = true

//        if (mCallPhone) {
//            mCallPhone = false
//            showSelectedTypeDialog()
//        }
    }

    override fun onPause() {
        super.onPause()
        mIsShow = false

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK || data == null) {
            return
        }
        if (supportFragmentManager.fragments.size > 0) {
            val fragments = supportFragmentManager.fragments
            for (fragment in fragments) {
                fragment.onActivityResult(requestCode, resultCode, data)
            }
        }

    }


    /**
     * 打开微信小程序
     */
    fun toMini() {
        val weChatPackageName = "com.tencent.mm"
        val isInstalled = YgxUtilsKt.isInstalled(weChatPackageName)
        if (isInstalled) {
            val mIWXAPI = WXAPIFactory.createWXAPI(this, Constants.WXAPP_ID)
            val req = WXLaunchMiniProgram.Req()
//            req.userName = "wx8b3acbaf67cbd53a"
            req.userName = mCompanyItemBean?.wxghid
            //req.path = path; //拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
            req.miniprogramType =
                WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
            mIWXAPI.sendReq(req)
        } else {
            showToast("请先安装微信")
        }
    }

    private var mPhones = mutableListOf<CommonSelectedBean>()

    private fun showPhonePopSelected() {
        if (mPhones.size == 1) {
            mPhone = mPhones[0].name ?: ""
            YgxUtilsKt.callPhone(this, mPhone)
            sendCallMessage()
            return
        }
        val mPopupView =
            ListSingleTextPopupView(
                this, mPhones
            ) { current, data ->
                if (current != -1) {
                    mPhone = data.name ?: ""
                    YgxUtilsKt.callPhone(this, mPhone)
                    savecallnum()
                    sendCallMessage()
                }

            }

        XPopup.Builder(this)
            .isViewMode(true)//对于只使用一次的弹窗，推荐设置这个
            .popupPosition(PopupPosition.Bottom)
            .asCustom(mPopupView)
            .show()
    }


    private var mHintDialog: HintDialog? = null
    private fun showHintDialog() {
        mHintDialog = HintDialog(this, "提示", "该店铺暂未开通此功能", true, true, {
//            ARouter.getInstance().build(ARoutUtils.JoinPlatformActivity).navigation()
        }, false)
        mHintDialog?.show()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.view_tel -> showPhonePopSelected()
            R.id.iv_back -> finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()

        if (mHintDialog?.isShowing == true) {
            mHintDialog?.dismiss()
        }

    }


}